from django.shortcuts import render
from django.http import JsonResponse,HttpResponseRedirect
from rest_framework.views import APIView
from rest_framework.response import Response
from tusers.models import *
from tools.sf import factory

from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync

class TestView(APIView):
    def get(self,request):
        room = request.GET.get('room')
        channel_layer = get_channel_layer()
        send_data = {"name":'234','idcard':'332424234'}
        async_to_sync(channel_layer.group_send)(
            room,#房间组名
            {
                'type':'send_to_chrome', #消费者中处理的函数
                'data':send_data
            }
        )
        return JsonResponse({"code":200,"msg":"更新数据成功"})
        # return Response({"code":200})
    
class Sfurl(APIView):
    def get(self,request):
        qurl = factory.create_factory('qq')
        # print(qurl.geturl())
        durl = factory.create_factory('dinding')
        return Response({"code":200,'qqurl':qurl.geturl(),'ddurl':durl.geturl()})
        # return Response({"code":200})
        
def sflogincallback(user):
    #user {"name":name,'uid':uid,'phone':phone}
    uid = user['uid']
    
    #查询三方登录表
    #存在查询用户调用jwt生成token，跳转到中转页面
    #如果不存在，写入用户表，写入三方登录表，调用jwt生成token，跳转到中转页面
   
    
        
class SfCallback(APIView):
    def get(self,request):
        durl = factory.create_factory('dinding')
        code = request.GET.get('code')
        user = durl.callback(code)
        sflogincallback(user)

class SfQQCallback(APIView):
    def get(self,request):
        durl = factory.create_factory('qq')
        code = request.GET.get('code')
        user = durl.callback(code)
        sflogincallback(user)  
        
        
from qiniu import Auth    
def getqntoken(request):
   
    #需要填写你的 Access Key 和 Secret Key
    access_key = '10XJP3-oMzY2Ghrwsm6nc-fr1OKu_-HcRwweQ1AB'
    secret_key = 'L3yUOFzGq3zJwqy924JPvMg61H88COZZ8feUcAJj'
    #构建鉴权对象
    q = Auth(access_key, secret_key)
    #要上传的空间
    bucket_name = 'h2402a'
    #上传后保存的文件名
    # key = ''
    # #生成上传 Token，可以指定过期时间等
    # # 上传策略示例
    # # https://developer.qiniu.com/kodo/manual/1206/put-policy
    # policy = {
    # # 'callbackUrl':'https://requestb.in/1c7q2d31',
    # # 'callbackBody':'filename=$(fname)&filesize=$(fsize)'
    # # 'persistentOps':'imageView2/1/w/200/h/200'
    # }
    #3600为token过期时间，秒为单位。3600等于一小时
    token = q.upload_token(bucket_name)
    return JsonResponse({"code":200,'token':token})
         
from tools.baiduapi import bdapi
from tools.myredis import r   

from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync

class PicCode(APIView):
    def get(self,request):
        purl = request.GET.get("picurl")
        # res = bdapi.piccode(purl)
        #将图片地址加入到redis队列
        r.list_push('idcardlist',purl)
        return Response({"code":200,'mes':'正在处理中'})
    def post(self,request):
        purl = request.data.get("picurl")
        channel_layer = get_channel_layer()
        send_data = {"name":'张三','idcard':'332424234'}
        async_to_sync(channel_layer.group_send)(
            purl,#房间组名
            {
                'type':'send_to_chrome', #消费者中处理的函数
                'data':send_data
            }
        )
        return JsonResponse({"code":200,"msg":"更新数据成功"})
       

from elasticsearch import Elasticsearch
# 创建es 实例
es = Elasticsearch("http://39.105.220.219:9200/")
class EsSearch(APIView):
    def post(self,request):
        # 把医生表中的数据和健康知识表中的数据获取到写入es   id、title、message,将最后一个id放入redis缓存中
        doctor = Doctor.objects.all().order_by('-id')
        maxid = 0
        number = 0
        for i in doctor:
            es.index('doctor',body={})
            if number == 0:
                maxid = i.id
            number+=1
        r.set_str('dotormaxid',maxid)
        # for i in range(5):
        #     es.index('news_test',body={"id":i,'title':'新闻'+str(i)})
        return Response({"code":200})
    
    def get(self,request):
        smes = "娱乐"
        # for i in range(10):
        #     es.index(index='test1', body={
        #         'id': i,
        #         # 'table_name': 'test',
        #         'name': '娱乐'+str(i),
        #         'age': i,
        #     })
            
        dsl={
            "query":{
                "match":{"name":smes}
            }

        }
        res = es.search(index="test1", body=dsl)
        print(res['hits']['hits'])
            
        # sname = request.GET.get('sname')
        # #获取第几页数据
        # page = request.GET.get('page')
        # #每页显示多少条
        # page_size=2
        # #
        # start = (int(page)-1)*page_size
        
        
        # smes = {
        #     "query":{
        #         "match":{"title":sname}
        #     },
        #     "from":start,
        #     "size":page_size,
        #     "_source":["id","title"],
        #     "sort":{
        #         "id":{
        #             "order":"desc"
        #         }
        #     }
        # }
       
        # data = es.search('news_test',smes)
        # print(data)
        return Response({"code":200,'mes':'me3333s'})